<template>
  <header>
    <div @click="goBack">
      <van-icon name="arrow-left" color="#fff" />
    </div>
    <div class="search">
      <van-icon name="search" size="20" />
    </div>
    <slot>
      <form
        onsubmit="return false"
        action=""
        class="search-input"
        @keyup.enter="goSearchList"
      >
        <input
          type="search"
          placeholder="请输入搜索关键字"
          v-model="searchVal"
        />
      </form>
    </slot>
    <div class="search-text" @click="goSearchList">搜索</div>
  </header>
</template>

<script>
export default {
  props: {
    queryKey: String,
  },
  data() {
    return {
      searchVal: this.queryKey,
      searchArr: [],
    };
  },
  methods: {
    //返回上一页
    goBack() {
      this.$router.back();
    },
    //搜索事件
    goSearchList() {
      //没有搜索值，不进行搜索
      if (!this.searchVal) return;

      //判断之前有没有本地存储
      if (!localStorage.getItem("searchList")) {
        //没有
        localStorage.setItem("searchList", "[]");
      } else {
        //之前有
        this.searchArr = JSON.parse(localStorage.getItem("searchList"));
      }
      //增加数据
      this.searchArr.unshift(this.searchVal);
      // 去重
      let obj = new Set(this.searchArr);
      // //给本地存储赋值
      localStorage.setItem("searchList", JSON.stringify(Array.from(obj)));
      //跳转页面
      this.$router.push({
        path: "/search-list",
        query: {
          key: this.searchVal,
        },
      });

      this.searchVal = "";
    },
  },
};
</script>

<style scoped lang="less">
header {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 48px;
  background-color: #ef4645;
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 20;
  .search {
    position: relative;
    left: 40px;
    bottom: 0;
  }
  .search-input {
    // width: 70%;
    background-color: #f5f7f9;
    line-height: 28px;
    border-radius: 10px;
    overflow: auto;

    input {
      padding-left: 25px;
      font-size: 15px;
      // width:70%;
      background-color: #f5f7f9;
    }
  }
  .search-text {
    font-size: 14px;
    margin: 0 10px 0 10px;
    color: #fff;
  }
}
</style>
